package com.woniuxy.third.utils;

import com.woniuxy.third.result.ResponseResult;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.util.ArrayList;
import java.util.List;

/**
 * @Author: yangtao
 * @date 2021/7/20 11:16
 * @Version 1.0
 */
public class FileUploadUtil {
    public static List<String> multifileUpload(HttpServletRequest request){

        List<MultipartFile> files = ((MultipartHttpServletRequest)request).getFiles("file");
        List<String> list = new ArrayList<>();
        if(files.isEmpty()){
            list.add("文件为空");
            return list;
        }

        String path = "D:/webStormWorkspace/third-web/static/image";
        for(MultipartFile file:files){
            String fileName = file.getOriginalFilename();
            int size = (int) file.getSize();
            if(size>10485760L){
                list.add("文件内存超限，请上传小于10mb文件");
                return list;
            }

            if(file.isEmpty()){
                list.add("文件为空");
                return list;
            }else{
                File dest = new File(path + "/" + fileName);
                if(!dest.getParentFile().exists()){ //判断文件父目录是否存在
                    dest.getParentFile().mkdir();
                }
                try {
                    if(fileName.endsWith("png")||fileName.endsWith("jpg")){
                        file.transferTo(dest); //保存文件
                        list.add("/static/image/"+fileName);
                    }else {
                        list.add("文件格式错误");
                        return list;
                    }
                }catch (Exception e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                    list.add("保存失败");
                    return list;
                }
            }
        }
        list.add("保存成功");
        return list;
    }
}
